{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "bf8daf74",
   "metadata": {},
   "source": [
    "# Lesson 2: Explore Carbon Intensity on the Grid"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fda9feb1",
   "metadata": {},
   "source": [
    "* In this classroom, the libraries have been already installed for you.\n",
    "* If you would like to run this code on your own machine, make sure to get your Electricity Maps API from their [website](https://www.electricitymaps.com/free-tier-api)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3c6233fd",
   "metadata": {},
   "source": [
    "#### Load the Electricity Maps API for this notebook"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "602dfe5d-37f6-4580-800a-03111ad0d541",
   "metadata": {
    "height": 47
   },
   "outputs": [],
   "source": [
    "from helper import load_env\n",
    "load_env()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cd20c065",
   "metadata": {},
   "source": [
    "### Electricity Map's live carbon intensity  endpoint"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4370c756",
   "metadata": {},
   "source": [
    "* Set location coordinates.\n",
    "\n",
    "Remember, you can get the coordinates from [Google Maps](https://www.google.com/maps)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a9ee6f67-5204-4788-9d1b-ac0a99430f11",
   "metadata": {
    "height": 98
   },
   "outputs": [],
   "source": [
    "# Create a dictionary with the coordinates\n",
    "coordinates = {\n",
    "    \"lat\":34.00906474557528,\n",
    "    \"lon\": -118.4984580927553\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ddf56ac6",
   "metadata": {},
   "source": [
    "* Request from the endpoint."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0ce64337-fc26-4e2b-b65f-3c6012152103",
   "metadata": {
    "height": 98
   },
   "outputs": [],
   "source": [
    "# Build the url\n",
    "url= f\"https://api.electricitymap.org/v3/carbon-intensity/latest?lat={coordinates['lat']}&lon={coordinates['lon']}\"\n",
    "\n",
    "# Print the endpoint\n",
    "print(\"Endpoint: \" + str(url))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7d3c91f9",
   "metadata": {},
   "source": [
    "* Prepare the get request."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b9f244e1-4422-4cd1-9762-0dbf2e0574d9",
   "metadata": {
    "height": 47
   },
   "outputs": [],
   "source": [
    "import requests\n",
    "import helper"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "42416461-5d7d-48eb-a127-91c5cd3dbe6d",
   "metadata": {
    "height": 64
   },
   "outputs": [],
   "source": [
    "request = requests.get(\n",
    "    url,\n",
    "    headers={\"auth-token\": helper.load_emaps_api_key()})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "945c64c6",
   "metadata": {
    "height": 64
   },
   "outputs": [],
   "source": [
    "# This byte format is more compact\n",
    "request.content\n",
    "type(request.content)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "575d6227",
   "metadata": {},
   "source": [
    "> Note: This byte format is more compact and often not human-readable. Additionally, it is not possible to access the fields within this byte data as we would access with key-value pairs in a dictionary. This is why we use json.loads()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "800e8a18-a9a1-4bcc-b1d0-37aadea63899",
   "metadata": {
    "height": 30
   },
   "outputs": [],
   "source": [
    "import json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e0ef54b3-931a-40cc-a462-ce2ea8bdf056",
   "metadata": {
    "height": 30
   },
   "outputs": [],
   "source": [
    "json.loads(request.content)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5771a717",
   "metadata": {},
   "source": [
    "* Use the live power breakdown endpoint."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3002e353-003b-48c2-9d47-fb0672eed6bd",
   "metadata": {
    "height": 47
   },
   "outputs": [],
   "source": [
    "# Build the url\n",
    "url = f\"https://api.electricitymap.org/v3/power-breakdown/latest?lat={coordinates['lat']}&lon={coordinates['lon']}\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "21bf397d-59e5-49af-a51a-6d9a9517a87b",
   "metadata": {
    "height": 30
   },
   "outputs": [],
   "source": [
    "print(url)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b043cc11-943e-4257-b07f-f3443c33e9d0",
   "metadata": {
    "height": 64
   },
   "outputs": [],
   "source": [
    "request = requests.get(\n",
    "    url,\n",
    "    headers={\"auth-token\": helper.load_emaps_api_key()})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d59b6fff-a851-45ff-8b3e-9bb7a987bebf",
   "metadata": {
    "height": 81
   },
   "outputs": [],
   "source": [
    "power_breakdown = json.loads(request.content)\n",
    "\n",
    "# Print the content\n",
    "power_breakdown"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9b79e401",
   "metadata": {},
   "source": [
    "* Print some specific values."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2cd3ed06-9b38-4d25-bb7e-264a1f5d2567",
   "metadata": {
    "height": 30
   },
   "outputs": [],
   "source": [
    "power_breakdown['renewablePercentage']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c4af92e5-46fd-4e19-9524-15087d57db0e",
   "metadata": {
    "height": 30
   },
   "outputs": [],
   "source": [
    "power_breakdown['fossilFreePercentage']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8afc2237-fb73-4820-bc2f-e75c80904c1a",
   "metadata": {
    "height": 47
   },
   "outputs": [],
   "source": [
    "# Power Consumption Breakdown in MegaWatts\n",
    "power_breakdown['powerConsumptionBreakdown']"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bfbe54e7",
   "metadata": {},
   "source": [
    "* Do some math to understand better the values above."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9da7b057-860c-4fcb-a586-3545a4935235",
   "metadata": {
    "height": 30
   },
   "outputs": [],
   "source": [
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "063e7626-ac4b-4e55-9b48-e13ea5833c12",
   "metadata": {
    "height": 30
   },
   "outputs": [],
   "source": [
    "total_consumption = power_breakdown['powerConsumptionTotal']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "23479db7-45bc-4636-8973-920e8b794106",
   "metadata": {
    "height": 30
   },
   "outputs": [],
   "source": [
    "total_consumption"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8e6a3639-0a8f-4a7e-b02d-0cc18737778e",
   "metadata": {
    "height": 98
   },
   "outputs": [],
   "source": [
    "consumption_percent = {\n",
    "    k: np.round((v/total_consumption) * 100)\n",
    "    for k,v\n",
    "    in power_breakdown['powerConsumptionBreakdown'].items()}\n",
    "consumption_percent"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "45d80161",
   "metadata": {},
   "source": [
    "#### Helper function for the power_stats"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cc958713-b0b1-4052-8102-18ac54c6ccea",
   "metadata": {
    "height": 421
   },
   "outputs": [],
   "source": [
    "import helper, requests, json, numpy as np\n",
    "def power_stats(lat,lon, api_key=helper.load_emaps_api_key()):\n",
    "    coordinates = { \"lat\": lat, \"lon\": lon }\n",
    "\n",
    "    url_intensity = f\"https://api.electricitymap.org/v3/carbon-intensity/latest?lat={coordinates['lat']}&lon={coordinates['lon']}\"\n",
    "    request_intensity = requests.get(url_intensity, headers={\"auth-token\": api_key})\n",
    "    intensity = json.loads(request_intensity.content)\n",
    "\n",
    "    url_breakdown = f\"https://api.electricitymap.org/v3/power-breakdown/latest?lat={coordinates['lat']}&lon={coordinates['lon']}\"\n",
    "    request_breakdown = requests.get(url_breakdown, headers={\"auth-token\": api_key})\n",
    "    breakdown = json.loads(request_breakdown.content)\n",
    "\n",
    "    breakdown_abridged = {\n",
    "        'renewablePercentage': breakdown['renewablePercentage'],\n",
    "        'fossilFreePercentage': breakdown['fossilFreePercentage'],\n",
    "        'powerConsumptionBreakdown': breakdown['powerConsumptionBreakdown'],\n",
    "        'consumption_percent': {\n",
    "            k: np.round((v/breakdown['powerConsumptionTotal']) * 100) \n",
    "            for k, v \n",
    "            in breakdown['powerConsumptionBreakdown'].items()\n",
    "        },\n",
    "    }\n",
    "    \n",
    "    return intensity, breakdown_abridged"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bf999bac-2878-4c88-af91-6be919c37115",
   "metadata": {
    "height": 81
   },
   "outputs": [],
   "source": [
    "# Coordinates from a landmark in Taiwan, shown by the instructor in the explanation\n",
    "intensity, breakdown = power_stats(\n",
    "    lat=25.0356575108668,\n",
    "    lon=121.52010809479746)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ea3d6ea9-1a0d-4226-8afc-9e6652040919",
   "metadata": {
    "height": 30
   },
   "outputs": [],
   "source": [
    "intensity"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e1ce94fa-8103-4b11-9c6e-9da06143fa54",
   "metadata": {
    "height": 30
   },
   "outputs": [],
   "source": [
    "breakdown"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4858a219",
   "metadata": {},
   "source": [
    "### Do it yourself! \n",
    "* Get coordinates from a location you want to retrieve the information we got before!"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
